'use strict';
/**
 * 图片裁剪通用组件基于图片裁剪组件cropper
 * author: colpu
 * function: comicCropper
 */
function ComicCropper() {
  this.URL = window.URL || window.webkitURL; // 获得原生的URL
  this.uploadedImageType = ''; // image/jpeg
  this.uploadedImageName = ''; // 要上传的图片名称
  this.uploadedImageURL = null;//缓存在URL临时blob中的url
  this.cropper = null; //缓存的cropper对象
  this.container = null; // 要裁剪的图片盒子
  this.image = null; // 裁剪的图片
  this.actions = null; // 对裁剪方式重新设置
  this.options = {
    aspectRatio: 2, // 默认裁剪比例2:1
    preview: '.preview-cropper-img', // 预览裁剪图片
    ready: function(e) {
      // console.log(e.type);
    },
    cropstart: function(e) {
      // console.log(e.type, e.detail.action);
    },
    cropmove: function(e) {
      // console.log(e.type, e.detail.action);
    },
    cropend: function(e) {
      // console.log(e.type, e.detail.action);
    },
    crop: function(e) {
      // console.log(e.type, data);
    },
    zoom: function(e) {
      // console.log(e.type, e.detail.ratio);
    },
    cropperDataType: true, // 设置裁剪数据类型
    getCropperData: null // 获得裁剪数据方法
  };
}
ComicCropper.prototype = {
  /**
   * 初始化方法
   * parmas [Object] opt为json对象
   */
  init: function(opt) {
    if (!opt && !opt.container) {
      throw ('必须设置container图片')
    };
    var _this = this;
    _this.container = document.querySelector(opt.container);
    _this.image = _this.container.getElementsByTagName('img').item(0);
    // 创建实例
    this.cropper = new Cropper(_this.image, Object.assign(_this.options, opt));

    // 绑定变化参数
    _this.actions = document.querySelector(opt.actions);
    _this.actions.querySelector('.docs-toggles').onchange = function(event) {
      _this.changeHandle(event, _this);
    };
    _this.actions.querySelector('.docs-buttons').onclick = function(event) {
      var that = this;
      _this.clickHandle(event, _this, that);
    };

    _this.bindFileReload(document.getElementById(opt.inputImage));
  },
  /**
   * 改变设置重新实例化裁剪
   */
  changeHandle: function(event, _this) {
    var e = event || window.event;
    var target = e.target || e.srcElement;
    var cropBoxData, canvasData, isCheckbox, isRadio;
    var cropper = _this.cropper;
    var options = _this.options;
    if (!cropper) {
      return;
    }

    if (target.tagName.toLowerCase() === 'label') {
      target = target.querySelector('input');
    }

    isCheckbox = target.type === 'checkbox'; // 是否为checkbox
    isRadio = target.type === 'radio';

    if (isCheckbox || isRadio) {
      if (isCheckbox) {
        options[target.name] = target.checked;
        cropBoxData = cropper.getCropBoxData();
        canvasData = cropper.getCanvasData();
        options.ready = function() {
          console.log('ready canvas');
          // 将数据重新设置到canvas
          cropper.setCropBoxData(cropBoxData).setCanvasData(canvasData);
        };
      } else {
        options[target.name] = target.value;
        options.ready = function() {
          // console.log('ready');
        };
      }

      // 释放老的裁剪重新设置新的裁剪
      cropper.destroy();
      _this.cropper = new Cropper(_this.image, options); // 这里要用_this.cropper重新设置裁剪实例对象
    }
  },
  /**
   * 点击操作裁剪
   */
  clickHandle: function(event, _this, that) {
    var e = event || window.event;
    var target = e.target || e.srcElement;
    var result, input, data;
    var cropper = _this.cropper;
    var uploadedImageType = _this.uploadedImageType;
    var uploadedImageURL = _this.uploadedImageURL;

    if (!cropper) {
      return;
    }
    while (target !== that) {
      if (target.getAttribute('data-method')) {
        break;
      }
      target = target.parentNode;
    }

    if (target === that || target.disabled || target.className.indexOf('disabled') > -1) {
      return;
    }

    data = {
      method: target.getAttribute('data-method'),
      target: target.getAttribute('data-target'),
      option: target.getAttribute('data-option'),
      secondOption: target.getAttribute('data-second-option')
    };

    if (data.method) {
      if (typeof data.target !== 'undefined') {
        input = document.querySelector(data.target);

        if (!target.hasAttribute('data-option') && data.target && input) {
          try {
            data.option = JSON.parse(input.value);
          } catch (e) {
            console.log(e.message);
          }
        }
      }

      switch (data.method) {
        case 'rotate':
          cropper.clear();
          break;

        case 'getCroppedCanvas':
          try {
            data.option = JSON.parse(data.option);
            //强制图片外的地方透明
              if(data.option===null){
                data.option={
                    fillColor:"rgba(0,0,0,0)"
                }
              }

          } catch (e) {
            console.log(e.message);
          }

          if (uploadedImageType === 'image/jpeg') {
            if (!data.option) {
              data.option = {};
            }
            data.option.fillColor = '#fff';
          }
          break;
      }

      result = cropper[data.method](data.option, data.secondOption);
      switch (data.method) {
        case 'rotate':
          cropper.crop();
          break;
        case 'scaleX':
        case 'scaleY':
          target.setAttribute('data-option', -data.option);
          break;
        case 'getCroppedCanvas':
          if (result) {
            // 获得图片上传数据
            if (!_this.options.getCropperData) return;
            if (_this.options.cropperDataType) {
              _this.options.getCropperData(result.toDataURL(uploadedImageType))
            } else {
              result.toBlob(function(file) {
                _this.options.getCropperData(file)
              });
            }
          }
          break;
        case 'destroy':
          cropper = null;
          if (uploadedImageURL) {
            _this.URL.revokeObjectURL(uploadedImageURL);
            _this.uploadedImageURL = '';
            image.src = originalImageURL;
          }
          break;
      }
      if (typeof result === 'object' && result !== cropper && input) {
        try {
          input.value = JSON.stringify(result);
        } catch (e) {
          console.log(e.message);
        }
      }
    }
  },
  /**
   * 为inputfile绑定重新上传图片裁剪
   * parms: [Object] obj为inputfile 的id
   */
  bindFileReload: function(obj) {
    var _this = this;
    var URL = _this.URL;
    if (URL) {
      obj.onchange = function() {
        var files = this.files;
        var file;
        if (_this.cropper && files && files.length) {
          file = files[0];
          if (/^image\/\w+/.test(file.type)) {
            _this.reloadImg(file);
            // obj.value = null;
          } else {
            window.alert('请重新选择图片！');
          }
        }
      };
    } else {
      obj.disabled = true;
      obj.parentNode.className += ' disabled';
    }
  },
    /*
    *    根据指定file对象或blob对象重载图片裁剪
    *    param: file[file/blob对象]   blobName:如果传入的是blob对象，请传入自定义name，否则为默认为custom
    * */
    reloadImg:function(file,blobName){
        var _this = this;
        var URL = _this.URL;
        var uploadedImageURL = _this.uploadedImageURL;
        if(URL){
          if(typeof file==="string") {
              _this.uploadedImageName = file;
              _this.image.src = _this.uploadedImageURL=file;
          }
          else{
              if(!file.name){
                  _this.uploadedImageName=blobName||"custom."+file.type.replace(/image\//,"");
              }
              else {
                  _this.uploadedImageName = file.name;
              }
              if (uploadedImageURL) {
                  URL.revokeObjectURL(uploadedImageURL);
              }
              _this.image.src = _this.uploadedImageURL = URL.createObjectURL(file);
          }
          _this.cropper.destroy();
          _this.cropper = new Cropper(_this.image, _this.options);
        }
        else {
          console.log("客户端不支持此重载图片方法！");
        }
    }
};